import React, { useEffect, useRef, useState } from 'react';
import { Button } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';

interface CaptchaProps {
  width?: number;
  height?: number;
  length?: number;
  onChange?: (code: string) => void;
}

const Captcha: React.FC<CaptchaProps> = ({
  width = 120,
  height = 40,
  length = 4,
  onChange
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [captchaCode, setCaptchaCode] = useState('');

  // 生成随机字符
  const generateRandomChar = () => {
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    return chars[Math.floor(Math.random() * chars.length)];
  };

  // 生成随机颜色
  const getRandomColor = (min: number = 0, max: number = 255) => {
    const r = Math.floor(Math.random() * (max - min + 1)) + min;
    const g = Math.floor(Math.random() * (max - min + 1)) + min;
    const b = Math.floor(Math.random() * (max - min + 1)) + min;
    return `rgb(${r},${g},${b})`;
  };

  // 绘制验证码
  const drawCaptcha = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    // 设置背景
    ctx.fillStyle = '#f8f9fa';
    ctx.fillRect(0, 0, width, height);

    // 生成验证码
    let code = '';
    for (let i = 0; i < length; i++) {
      code += generateRandomChar();
    }
    setCaptchaCode(code);
    onChange?.(code);

    // 绘制字符
    const charWidth = width / length;
    for (let i = 0; i < length; i++) {
      const char = code[i];
      const x = charWidth * i + charWidth / 2;
      const y = height / 2;

      // 随机字体大小和颜色
      const fontSize = Math.floor(Math.random() * 8) + 20;
      ctx.font = `${fontSize}px Arial`;
      ctx.fillStyle = getRandomColor(50, 150);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      // 随机旋转角度
      const angle = (Math.random() - 0.5) * 0.5;
      ctx.save();
      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.fillText(char, 0, 0);
      ctx.restore();
    }

    // 绘制干扰线
    for (let i = 0; i < 5; i++) {
      ctx.strokeStyle = getRandomColor(100, 200);
      ctx.lineWidth = Math.random() * 2;
      ctx.beginPath();
      ctx.moveTo(Math.random() * width, Math.random() * height);
      ctx.lineTo(Math.random() * width, Math.random() * height);
      ctx.stroke();
    }

    // 绘制干扰点
    for (let i = 0; i < 30; i++) {
      ctx.fillStyle = getRandomColor(150, 200);
      ctx.beginPath();
      ctx.arc(
        Math.random() * width,
        Math.random() * height,
        Math.random() * 2,
        0,
        2 * Math.PI
      );
      ctx.fill();
    }
  };

  // 刷新验证码
  const refreshCaptcha = () => {
    drawCaptcha();
  };

  useEffect(() => {
    drawCaptcha();
  }, []);

  return (
    <div style={{ 
      display: 'flex', 
      alignItems: 'center', 
      gap: '8px',
      border: '1px solid #d9d9d9',
      borderRadius: '6px',
      padding: '4px',
      background: 'white'
    }}>
      <canvas
        ref={canvasRef}
        width={width}
        height={height}
        style={{
          cursor: 'pointer',
          borderRadius: '4px',
        }}
        onClick={refreshCaptcha}
      />
      <Button
        type="text"
        icon={<ReloadOutlined />}
        size="small"
        onClick={refreshCaptcha}
        className="captcha-refresh"
        style={{
          color: '#667eea',
          border: 'none',
          boxShadow: 'none',
        }}
        title="点击刷新验证码"
      />
    </div>
  );
};

export default Captcha;
